package com.tingyuge.base.structrue.unio;

/**
 * @Created by xiaodao
 */
public class UnionFind1 implements UnionFind {

    private int[] id;

    //并查集考虑的元素
    public UnionFind1(int size){
        this.id = new int[size];

        //每一个元素对应的集合编号
        for (int i = 0; i <id.length ; i++) {
            id[i] = i;

        }
    }

    @Override
    public int getSize() {
        return id.length;
    }

    //查看元素p和元素q是否属于一个集合
    @Override
    public boolean isConnected(int p, int q) {
        return id[p] == id[q];
    }
    //合并元素p和元素q
    @Override
    public void unionElements(int p, int q) {
        int pid = find(p);
        int qid = find(q);
        if(pid == qid){
            return;
        }
        for (int i = 0; i <id.length ; i++) {
           if(id[i] ==qid) {
               id[i] = pid;
           }

        }
    }
    //返回元素p对应的集合编号
    private int find(int p){
        if(p < 0 || p >id.length){
            throw  new IllegalArgumentException("p is not found");
        }
        return id[p];
    }
}
